package com.authine.cloudpivot.engine.plugin.service.impl;

import com.authine.cloudpivot.engine.plugin.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    @PersistenceContext
    EntityManager entityManager;

    @Override
    public List<Map<String, Object>> getListByMap(Map<String, Object> map) {

        String sql = (String) map.get("sql");
        Map<String,Object> parameterMap = (Map<String, Object>) map.get("parameter");

        Query query = entityManager.createNativeQuery(sql);

        if (MapUtils.isNotEmpty(parameterMap)) {
            parameterMap.forEach((k,v)->{
                query.setParameter(k, v);
            });
        }
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        List<Map<String, Object>> resultList = query.getResultList();


        log.info("进入自定义sql 查询结果:{}",resultList);

        return resultList;
    }
}
